﻿using FDStudio.Core.Config;
using FDStudio.Core.Entities.Enums;
using FDStudio.Core.Runtime;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Text;

namespace FDStudio.Core.Extensions
{
    /*
     CreatedOn: 2018-01-31
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// appconfig扩展
    /// </summary>
    public static class AppConfigExtension
    {
        /// <summary>
        /// 使用配置
        /// </summary>
        /// <param name="services"></param>
        public static void AddConfig(this IServiceCollection services)
        {
            AppConfig config = null;
            try
            {
                using (FileStream fs = new FileStream(RuntimeContext.Current.RuntimePath.ConfigFile, FileMode.Open))
                {
                    StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                    var data = sr.ReadToEnd();
                    config = data.FromJson<AppConfig>();
                }
            }
            catch (Exception ex)
            {
            }
            if (config == null)
            {
                config = AppConfig.Default();
            }
            RuntimeContext.Current.AppConfig = config;
        }

        /// <summary>
        /// 是否包含指定操作类型
        /// 空值/读写，即包含
        /// </summary>
        /// <param name="operType"></param>
        /// <param name="databaseOperType"></param>
        /// <returns></returns>
        public static bool HasOperType(this DatabaseOperType? operType, DatabaseOperType databaseOperType)
        {
            if (!operType.HasValue)
            {
                return true;
            }
            return operType.Value == databaseOperType || operType.Value == DatabaseOperType.ReadWrite;
        }

        /// <summary>
        /// 是否包含指定操作类型
        /// </summary>
        /// <param name="options"></param>
        /// <param name="databaseOperType"></param>
        /// <returns></returns>
        public static bool HasOperType(this ContextOptions options, DatabaseOperType databaseOperType)
        {
            return options.DatabaseOperType == databaseOperType ||
                    options.DatabaseOperType == DatabaseOperType.ReadWrite;
        }

        /// <summary>
        /// 添加单例服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="interfaceType"></param>
        /// <param name="implementType"></param>
        public static void AddSingleService(this IServiceCollection services, Type interfaceType, Type implementType)
        {
            int index = services.IndexOf(new ServiceDescriptor(interfaceType, implementType, ServiceLifetime.Singleton));
            if (index != -1)
            {
                services.RemoveAt(index);
            }
            services.AddSingleton(interfaceType, implementType);
        }

    }
}
